/**
 * @intro: http统一封装,同时支持callback模式调用.
 */
import axios from 'axios';
import { isFormData, judgeCode } from './verify';
import { enumContentType } from '@/common/enum';

let baseURL = process.env.NEXT_PUBLIC_BASE_API || '';
//注意服务端不会被代理所替换 需要手动替换
const isServer = typeof window === 'undefined'
if (isServer && process.env.NODE_ENV === "development") {
  baseURL = "http://stg.xinqiuzb.com:8200"
}
const service = axios.create({
  baseURL,
  headers: {
    'Content-Type': enumContentType.json,
  },
  timeout: 30000,
  responseType: 'json',
  // 请求转换
  transformRequest: [
    (data, headers) => {
      headers['hq-source'] = 2;
      headers['client-type'] = 'web';
      if (isFormData(data)) {
        headers['Content-Type'] = enumContentType.formData;
        return data;
      }
      try {
        if (typeof data === 'string') return data;
        return JSON.stringify(data);
      } catch (e) {
        return data;
      }
    },
  ],
});

service.interceptors.request.use((req) => {
  return req
})

// response拦截
service.interceptors.response.use(
  (response) => {
    const { data = {} } = response;
    // 请求成功
    if (judgeCode(data.code)) {
      if (data.data) return data.data
      return data
    }

    // eslint-disable-next-line
    return Promise.reject({
      ...data,
      msg: data.msg || data.message,
      type: 'business',
    });
  },
  (err) => {
    const resError = err.response || {};
    const { data } = resError;
    if (data && typeof data === 'string') {
      // eslint-disable-next-line
      return Promise.reject({
        code: resError.status || '500',
        msg: data,
        type: 'business',
      });
    }

    // eslint-disable-next-line
    return Promise.reject({
      code: resError.status || '500',
      msg: err.message || 'System Busy!',
      type: 'system',
    });
  },
);

export default service;
